import Vue from 'vue'
import VueRouter from 'vue-router'
import login from "view/users/login";
import MainLayout from "lay/MainLayout";
import store from "@/store"

Vue.use(VueRouter)

const routes = [
  {
    name:"login",
    path:"/login",
    component:login,
  },
  {
    name:"MainLayout",
    path:"/",
    component:MainLayout,
    redirect:'/index/index',
    children:[
      {
        name:'Home',
        path:'/index/index',
        component:()=>import('view/home/index')
      },
      {
        name:'image',
        path:'/image/index',
        component:()=>import('view/home/image')
      },
    ]
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to,from,next)=>{
  const token=store.getters.token;
  //如果有token，并且在登录页，跳转到首页
   if(token&&to.name==="login"){
     return next({name:"MainLayout"});
   }
  //如果没有token，并且不是登录页，跳转到登录页
    if(!token&&to.name !=="login"){
      return next({name:"login"});
    }
    next();
})

export default router
